package io.framework.modules.oss.controller;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.framework.common.annotation.LogOperation;
import io.framework.common.constant.Constant;
import io.framework.common.exception.ErrorCode;
import io.framework.common.page.PageData;
import io.framework.common.utils.Result;
import io.framework.common.validator.ValidatorUtils;
import io.framework.common.validator.group.AliyunGroup;
import io.framework.common.validator.group.QcloudGroup;
import io.framework.common.validator.group.QiniuGroup;
import io.framework.modules.oss.cloud.CloudStorageConfig;
import io.framework.modules.oss.cloud.OSSFactory;
import io.framework.modules.oss.entity.SysOssEntity;
import io.framework.modules.oss.service.SysOssService;
import io.framework.modules.sys.service.SysParamsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 文件上传
 */
@RestController
@RequestMapping("sys/oss")
@Api(tags = "文件上传")
public class SysOssController {

    @Autowired
    private SysOssService sysOssService;

    @Autowired
    private SysParamsService sysParamsService;

    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;

    private JSONObject getTxt(String path) {
        BufferedReader br = null;
        try {
            ClassPathResource resource = new ClassPathResource(path);
            br = new BufferedReader(new InputStreamReader(resource.getStream(), "UTF-8"));
            String result = "";
            String str = null;
            while ((str = br.readLine()) != null) {
                result += str;
            }
            System.out.println(result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(br);
        }
        return null;
    }

    @GetMapping("test")
    public Result<String> test() {
        CloudStorageConfig config = sysParamsService.getValueObject(KEY, CloudStorageConfig.class);
        JSONObject sys_oss = getTxt("oss/sys_oss.txt");
        JSONObject sys_oss_s = getTxt("oss/sys_oss_s.txt");
        JSONArray cdxx_lists = sys_oss.getJSONArray("cdxx_lists");
        JSONArray cdxx_s_lists = sys_oss_s.getJSONArray("cdxx_lists");
        List<Integer> uuids = new ArrayList<>();
        for (int i = 0; i < cdxx_s_lists.size(); i++) {
            uuids.add(cdxx_s_lists.getJSONObject(i).getInteger("uuid"));
        }
        List<SysOssEntity> list = new ArrayList<>();
        for (int i = 0; i < cdxx_lists.size(); i++) {
            JSONObject cdxx = cdxx_lists.getJSONObject(i);
            if (!uuids.contains(cdxx.getInteger("uuid"))) {
                continue;
            }
            try {
                SysOssEntity sysOssEntity = new SysOssEntity();
                sysOssEntity.setFileName(cdxx.getString("cdmc"));
                sysOssEntity.setUrl(config.getLocalDomain() + "/oss/" + cdxx.getString("cdmc") + ".png");
                sysOssEntity.setSysUrl(cdxx.getString("cdrkdz"));
                sysOssEntity.setUrlTypeName(cdxx.getString("cdflmc"));
                sysOssEntity.setAuth2(1);
                sysOssEntity.setClassify(cdxx.getString("xtjbmc").equals("国家") ? 1 : 2);
                sysOssEntity.setCreateDate(new Date());
                list.add(sysOssEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        sysOssService.insertBatch(list);
        return new Result<String>().ok("fail");
    }

    @GetMapping("page")
    @ApiOperation(value = "分页")
//	@RequiresPermissions("sys:oss:all")
    public Result<PageData<SysOssEntity>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysOssEntity> page = sysOssService.page(params);

        return new Result<PageData<SysOssEntity>>().ok(page);
    }

    @GetMapping("info")
    @ApiOperation(value = "云存储配置信息")
//    @RequiresPermissions("sys:oss:all")
    public Result<CloudStorageConfig> info() {
        CloudStorageConfig config = sysParamsService.getValueObject(KEY, CloudStorageConfig.class);

        return new Result<CloudStorageConfig>().ok(config);
    }

    @PostMapping
    @ApiOperation(value = "保存云存储配置信息")
    @LogOperation("保存云存储配置信息")
//	@RequiresPermissions("sys:oss:all")
    public Result saveConfig(@RequestBody CloudStorageConfig config) {
        //校验类型
        ValidatorUtils.validateEntity(config);

        if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }

        sysParamsService.updateValueByCode(KEY, JSONUtil.toJsonStr(config));

        return new Result();
    }

    @PostMapping("upload")
    @ApiOperation(value = "上传文件")
//	@RequiresPermissions("sys:oss:all")
    public Result<Map<String, Object>> upload(@RequestParam("file") MultipartFile file, String fileName, String urlTypeName, String sysUrl, Integer auth2, Integer classify) throws Exception {
        if (file.isEmpty()) {
            return new Result<Map<String, Object>>().error(ErrorCode.UPLOAD_FILE_EMPTY);
        }

        //上传文件
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), extension);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        ossEntity.setFileName(fileName);
        ossEntity.setUrlTypeName(urlTypeName);
        ossEntity.setSysUrl(sysUrl);
        ossEntity.setAuth2(auth2);
        ossEntity.setClassify(classify);
        sysOssService.insert(ossEntity);

        Map<String, Object> data = new HashMap<>(1);
        data.put("src", url);

        return new Result<Map<String, Object>>().ok(data);
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @LogOperation("删除")
//	@RequiresPermissions("sys:oss:all")
    public Result delete(@RequestBody Long[] ids) {
        sysOssService.deleteBatchIds(Arrays.asList(ids));

        return new Result();
    }

    @PostMapping("delete")
    @ApiOperation(value = "删除")
    @LogOperation("删除")
//	@RequiresPermissions("sys:oss:delete")
    public Result deleteBId(Long id) {

        sysOssService.deleteById(id);

        return new Result();
    }

}
